    //
//  LoginViewController.m
//  iShop
//
//  Created by svp on 1/10/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "ResourceLoader.h"
#import "TitleTextfieldCell.h"
#import "LoginRequest.h"
#import "ActivityIndicatorView.h"
#import "iShopAppDelegate.h"
#import "RegisterRequest.h"

@implementation LoginViewController

@synthesize tableView = _tableView;
@synthesize btnChooseFunction = _btnChooseFunction;
@synthesize btnDoFunction = _btnDoFunction;
@synthesize btnCancel = _btnCancel;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
		_loginMode = YES;
		infomation = [[NSMutableDictionary alloc] init];
    }
    return self;
}

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if (_loginMode) {
		return 1;
	}
	return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if (section == 0) {
		return @"Account";
	}
	if (!_loginMode) {
		return @"Account information";
	}
	return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
	return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if (section == 0) {
		return 2;
	}
	if (!_loginMode) {
		return 4;
	}
	return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 0) {
		TitleTextfieldCell* cell = (TitleTextfieldCell*)[tableView dequeueReusableCellWithIdentifier:@"TitleTextfieldCell"];
		if (!cell) {
			ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"TitleTextfieldCell"] autorelease];
			cell = (TitleTextfieldCell*)rc.resource;
			cell.delegate = self;
		}
		cell.textField.text = @"";
		cell.titleLabel.text = indexPath.row == 0? @"Username" : @"Password";
		cell.textField.secureTextEntry = indexPath.row == 1;
		cell.tag = indexPath.row;
		NSString *key = indexPath.row == 0?KUsername:KPassword;
		if ([infomation valueForKey:key]) {
			cell.textField.text = [infomation valueForKey:key];
		}
		return cell;
	}
	if (!_loginMode) {
		TitleTextfieldCell* cell = (TitleTextfieldCell*)[tableView dequeueReusableCellWithIdentifier:@"TitleTextfieldCell"];
		if (!cell) {
			ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"TitleTextfieldCell"] autorelease];
			cell = (TitleTextfieldCell*)rc.resource;
			cell.delegate = self;
		}
		cell.textField.secureTextEntry = NO;
		cell.tag = 2 + indexPath.row;
		cell.textField.text = @"";
		NSString *key;
		switch (indexPath.row) {
			case 0:
				cell.titleLabel.text = @"Name";
				key = KName;
				break;
			case 1:
				cell.titleLabel.text = @"Phone";
				key = KPhone;
				break;
			case 2:
				cell.titleLabel.text = @"Email";
				key = KEmail;
				break;
			case 3:
				key = KAddress;
				cell.titleLabel.text = @"Address";
				break;
			default:
				break;
		}
		if ([infomation valueForKey:key]) {
			cell.textField.text = [infomation valueForKey:key];
		}
		return cell;
	}
	return nil;
}

-(void) textFieldDidBeginEditing:(UITableViewCell*)cell
{
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, 380 - 216 + 35);
	[_tableView scrollRectToVisible:cell.frame animated:YES];
}


-(void) textFieldDidEndEditing:(UITableViewCell*)cell
{
	
	switch (cell.tag) {
		case 0:
			[infomation setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:KUsername];
			break;
		case 1:
			[infomation setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:KPassword];
			break;
		case 2:
			[infomation setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:KName];
			break;
		case 3:
			[infomation setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:KPhone];
			break;
		case 4:
			[infomation setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:KEmail];
			break;
		case 5:
			[infomation setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:KAddress];
			break;
		default:
			break;
	}
}

-(void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditTable)];
	
	// For selecting cell.
	gestureRecognizer.cancelsTouchesInView = NO;
	
	[_tableView addGestureRecognizer:gestureRecognizer];
	
	[gestureRecognizer release];
}

-(void) endEditTable
{
	[_tableView endEditing:YES];
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, 380);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

-(IBAction) changeFunctionPress:(id) sender
{
	_loginMode = !_loginMode;
	_btnChooseFunction.title = !_loginMode?@"Log in":@"Register";
	_btnDoFunction.title = _loginMode?@"Log in":@"Register";
	[_tableView reloadData];
}

-(IBAction) doFunctionPress:(id) sender
{
	[_tableView endEditing:YES];
	if (_loginMode) {
		NSString *username = [infomation valueForKey:KUsername];
		NSString *password = [infomation valueForKey:KPassword];
		if (username && username.length > 0 && password && password.length > 0) {
			LoginRequest *loginRequest = [[LoginRequest alloc] init];
			loginRequest.delegate = self;
			
			[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) startSpinner:@"Waiting"];
			[loginRequest makeRequest:infomation];
		}
		else {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Info" message:@"You have to fill in both fields" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
	}
	else {
		NSString *username = [infomation valueForKey:KUsername];
		NSString *password = [infomation valueForKey:KPassword];
		if (username && username.length > 0 && password && password.length > 0) {
			RegisterRequest *registerRequest = [[RegisterRequest alloc] init];
			registerRequest.delegate = self;
			
			[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) startSpinner:@"Waiting"];
			[registerRequest makeRequest:infomation];
		}
		else {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Info" message:@"You have to fill in all fields" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
	}

}

-(void) processRequestResult:(BOOL)result
{
	[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) stopSpinner];
	if (result) {
		[self.parentViewController dismissModalViewControllerAnimated:NO];
	}
}

-(IBAction) cancelPress:(id) sender
{
	[self.parentViewController dismissModalViewControllerAnimated:NO];
}


@end
